var questionId = getCookie("questionId")

$(function () {
    myColumns();
});

// XXX问卷答题情况明细
function getQuestionnaireAboutSchool() {
    $("#countTable").bootstrapTable('refresh');
}

function TableInit() {

    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function (mycolumns) {
        $('#countTable').bootstrapTable({
            url: httpRequestUrl + '/queryRecordCountAnswer',         //请求后台的URL（*）
            method: 'POST',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            //是否启用排序
            sortOrder: "asc",                   //排序方式
            sortStable: true,                   //是否排序
            queryParamsType: '',//默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
            dataType: 'json',
            paginationShowPageGo: true,
            showJumpto: true,
            pageNumber: 1, //初始化加载第一页，默认第一页
            queryParams: queryParams,//请求服务器时所传的参数
            sidePagination: 'server',//指定服务器端分页
            pageSize: 100,//单页记录数
            pageList: [100],//分页步进值
            search: false, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            silent: true,
            showRefresh: false,                  //是否显示刷新按钮
            showToggle: false,
            minimumCountColumns: 2,             //最少允许的列数
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: mycolumns,
            responseHandler: function (res) {
                if (res.code === "666") {
                    var answerInfo = res.data.list;
                    console.log(answerInfo);
                    var NewData = [];
                    if (answerInfo.length) {
                        for (var i = 0; i < answerInfo.length; i++) {
                            var dataNewObj = {
                                'id': '',
                                "answerName": '',
                                'answerBelong': '',
                                "endTime": '',
                                'longTime': '',
                                'answerSource': '',
                                'ipAddress': '',
                            };
                            var questionAnswerStr = answerInfo[i].questionAnswer;
                            if(questionAnswerStr){
                                //获取[]中的内容
                                var questionAnswer = questionAnswerStr.match(/\[(.*?)\]/)[1];
                                var questionAnswerArr = questionAnswer.split(",");
                                for (var j = 0; j < answerInfo[i].questionNum; j++) {
                                    dataNewObj['questionTitle' + j] = questionAnswerArr[j];
                                }
                            }
                            dataNewObj.id = answerInfo[i].id;
                            dataNewObj.answerName = answerInfo[i].answerName;
                            dataNewObj.answerBelong = answerInfo[i].answerBelong;
                            dataNewObj.endTime = answerInfo[i].endTime;
                            dataNewObj.longTime = answerInfo[i].longTime + "秒";
                            if (answerInfo[i].answerSource === "email") {
                                dataNewObj.answerSource = "邮件";
                            } else if (answerInfo[i].answerSource === "phone") {
                                dataNewObj.answerSource = "手机";
                            } else if (answerInfo[i].answerSource === "link") {
                                dataNewObj.answerSource = "链接";
                            } else {
                                dataNewObj.answerSource = "其他";
                            }
                            dataNewObj.ipAddress = answerInfo[i].ipAddress;
                            NewData.push(dataNewObj);
                        }
                        var data = {
                            total: res.data.total,
                            rows: NewData
                        };
                    } else {
                        var data = {
                            rows: NewData
                        };
                    }
                    return data;
                } else {
                    var data = {
                        rows: []
                    };
                    return data;
                }

            }
        });
    };

    // 得到查询的参数
    function queryParams(params) {
        var answerNameOrBelong = $("#keyWord").val();
        answerNameOrBelong = answerNameOrBelong === "" ? null : answerNameOrBelong;
        var questionId = getCookie("questionId");
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            pageNum: params.pageNumber,
            pageSize: params.pageSize,
            questionId: questionId,
            answerNameOrBelong: answerNameOrBelong,
        };
        return JSON.stringify(temp);
    }

    return oTableInit;
}

window.operateEvents = {
    //编辑
    'click #btn_count': function (e, value, row, index) {
        id = row.id;
        $.cookie('questionId', id);
    }
};

// 表格中按钮
function addFunctionAlty(value, row, index) {
    var btnText = '';
//详情
    btnText += "<a href=\"javascript:void(0);\" onclick=\"showDetail("
        + "'" + row.id + "'"
        + ")\" style=\" color: #277093;\">详情</a>&nbsp;&nbsp;";
    //删除
    btnText += "<a href=\"javascript:void(0);\" onclick=\"deleteAnswerInfo("
        + "'" + row.id + "'"
        + ")\" style=\" color: #f00;\">删除</a>";//#f9f9f9
    return btnText;
}

//生成表头
function myColumns() {
    var mycolumns = [{
        checkbox: true,
        visible: false
    }, {
        field: 'operation',
        title: '操作',
        width: '90px',
        align: 'center',
        events: operateEvents,//给按钮注册事件
        formatter: addFunctionAlty//表格中增加按钮
    }, {
        field: 'id',
        title: '序号',
        align: 'center',
        formatter: function (value, row, index) {
            return index + 1;
        }
    },
        {
            field: 'answerName',
            title: '提交人',
            align: 'center',
        },
        {
            field: 'answerBelong',
            title: '所属学校',
            align: 'center',
        },
        {
            field: 'endTime',
            title: '提交答卷时间',
            align: 'center',
            width: '200px',
        },
        {
            field: 'longTime',
            title: '所用时间',
            align: 'center',
        }, {
            field: 'answerSource',
            title: '来源',
            align: 'center',
        }, {
            field: 'ipAddress',
            title: '来自ip',
            align: 'center',
        },]
    //获取问卷题目信息
    var data = {
        questionId: getCookie("questionId")
    }
    $.ajax({
        type: "POST",
        url: httpRequestUrl + "/queryQuestionnaireQuestionTitle",
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            var questionTitleStr = result.data.questionTitle;
            //根据&分割字符串
            var questionTitleArray = questionTitleStr.split("&");
            for (var i = 0; i < questionTitleArray.length; i++) {
                if (questionTitleArray[i] !== "") {
                    var questionTitle = (i + 1) + "." + questionTitleArray[i];
                    var questionTitleObj = {
                        field: 'questionTitle' + i,
                        title: questionTitle,
                        align: 'center',
                    }
                    mycolumns.push(questionTitleObj);
                }
            }
            console.log(mycolumns)
            var oTable = new TableInit();
            oTable.Init(mycolumns);
        }
    })
}

//下载报告
function downloadAnswer() {
    $("#countTable").tableExport({
        type: "excel",
        escape: "false",
        fileName: getCookie("nameOfQuestionnaire") + '答题情况明细'
    });
}


//预览问卷
$('#ctl02_hrefView').click(function () {
    window.open('previewQuestionnaire.html?i=' + getCookie("questionId") + '&e0Rp=preview');
});

//回车事件
$(document).keydown(function (event) {
    if (event.keyCode === 13) {
        getQuestionnaireAboutSchool();
    }
});

//删除答卷信息
function deleteAnswerInfo(id) {

}

//显示答卷详细信息
function showDetail(id) {

}

